package com.carbeauty.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

 

/**
 * TODO 此处填写 class 信息
 * 
 * 
 * @date 2011-3-9 14:36:11
 */
/*
 * 文件处理工具类
 */
public class FileUtil {

	/**
	 * 文件不存在则返回null，
	 * 
	 * 把文件转为字节数组
	 * @param filePath
	 *            文件路径
	 * @return 字节数组
	 * @throws IOException
	 */
	public static byte[] fileToBytes(String filePath) throws IOException {
		byte[] content = null;
		File file = new File(filePath);
		FileInputStream in = null;
		ByteArrayOutputStream out = null;
		if (!file.exists())
			return content;
		try {
			in = new FileInputStream(file);
			out = new ByteArrayOutputStream(4096);
			byte[] temp_b = new byte[4096];
			int n;
			while ((n = in.read(temp_b)) != -1) {
				out.write(temp_b, 0, n);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw e;
				}

			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw e;
				}

			}
		}
		if (out != null) {
			content = out.toByteArray();
		}

		return content;
	}

	/**
	 * 文件不存在则返回null，
	 * 
	 * 
	 * 
	 * @param bytes
	 *            字节数组
	 * @return FileInputStream
	 * @throws IOException
	 * 把byte[]转为InputStream
	 */
	public static InputStream fileToInputStream(byte[] bytes)
			throws IOException {
		ByteArrayInputStream inp = null;
		if (bytes == null)
			return inp;
		inp = new ByteArrayInputStream(bytes);

		return inp;
	}

	/**
	 * 把二进制数据写到指定的文件中去.
	 * 
	 * 
	 * 
	 * @param bytes
	 *            二进制数组。
	 * @param filePath
	 *            文件路径
	 * @return 0 失败，1 成功
	 * @throws IOException
	 * 文件转为字节数组
	 */
	public static int bytesToFile(byte[] bytes, String filePath)
			throws IOException {
		if (bytes == null)
			return 0;
		File file = new File(filePath);
		FileOutputStream fos = new FileOutputStream(file);
		if (file.exists()) {
			file.delete();
		}
		fos.write(bytes);
		fos.flush();
		fos.close();
		return 1;

	}

	/**
	 * 删除文件
	 * 
	 * 
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 0 失败，1 成功
	 * @throws IOException
	 * 删除文件
	 */
	public static void deleteFile(String fileName) {
		try {
			File f = new File(fileName);
			if (!f.exists())
				return;
			int i = 0;
			while (!f.delete()) {// 确保文件删除
				i++;
				if (i > 10) {
					break;
				}
				System.gc();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件
	 * 
	 * 
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 0 失败，1 成功
	 * @throws IOException
	 * "删除文件
	 */
	public static void deleteFile(File f) {
		try {

			int i = 0;
			if (!f.exists())
				return;
			while (!f.delete()) {// 确保文件删除
				i++;
				if (i > 10) {
					break;
				}
				System.gc();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 
	 * 
	 * 
	 * @param oldfilePath
	 *            原来的文件路径
	 * @param newfilepath
	 *            新的文件路径
	 * @return
	 * @throws IOException
	 * 复制文件到新的文件路径
	 */
	public static void copyFileToNewPath(String oldfile, String newfilepath)
			throws Exception {

		FileInputStream fin = null;
		FileOutputStream fout = null;
		File file_in = null;
		File file_out = null;
		try {
			file_in = new File(oldfile);
			file_out = new File(newfilepath);

			if (!file_in.exists()) {

				throw new IOException("文件不存在：" + file_in.getAbsolutePath());

			}
			if (file_out.exists()) {

				throw new IOException("目标文件已经存在：" + file_out.getAbsolutePath());

			}
			if (file_in.getAbsolutePath().equals(file_out.getAbsolutePath())) {

				throw new IOException("源文件：" + file_in.getAbsolutePath()
						+ "目标文件：" + file_out.getAbsolutePath() + "是同一文件");

			}

			if (!file_out.exists())

			{
				File path = new File(newfilepath.substring(0, newfilepath
						.lastIndexOf(File.separator)));
				if (!path.exists())
					createFolder(path.getAbsolutePath());
				file_out.createNewFile();
			}

			fin = new FileInputStream(file_in);
			fout = new FileOutputStream(newfilepath);

			byte[] bytes = new byte[1024];

			int c;
			while ((c = fin.read(bytes)) != -1) {
				fout.write(bytes,0,c);
			}
			fin.close();
			fout.close();

		} catch (Exception ex) {
			ex.printStackTrace();
			if (fin != null)
				fin.close();
			if (fout != null)
				fout.close();
			throw ex;

		}

	}
	
	/**
	 * 创建目录
	 * @param absolutePath
	 */
		public static void createFolder(String path) {
			if(path==null||path.equals(""))
				return;
			path=path.replaceAll("\\\\","/").replaceAll("/+", "/").replaceAll("/$", "");
			File dir=new File(path);
			if(dir.exists()){
				
				if(dir.isDirectory())
					return;
				else
					throw new RuntimeException("File exists with specified path \""+path+"\"");
			}else{
				
				
				if(path.indexOf("/")>=0){
					String superDir=path.substring(0,path.lastIndexOf("/"));
					createFolder(superDir);
				}
				
				
				boolean success=dir.mkdir();
				if(!success)
					throw new RuntimeException("Create folder \""+path+"\" failed");
			}
		}

	

	/**
	 * 
	 * 移动文件到新的文件路径 //
	 * 
	 * 
	 * 
	 * @param oldfilePath
	 *            原来的文件路径
	 * @param newfilepath
	 *            新的文件路径
	 * @return
	 * @throws IOException
	 * 移动文件到新的文件路径
	 */
	public static void moveFileToNewPath(String oldfile, String newfilepath)
			throws Exception {
		FileInputStream fin = null;
		FileOutputStream fout = null;
		File file_in = null;
		File file_out = null;
		try {
			file_in = new File(oldfile);
			file_out = new File(newfilepath);
			if (!file_out.exists())

			{
				File path = null;
				if (newfilepath.lastIndexOf(File.separator) != -1) {
					path = new File(newfilepath.substring(0, newfilepath
							.lastIndexOf(File.separator)));

				} else {
					path = new File(newfilepath);

				}

				if (!path.exists())
					createFolder(path.getAbsolutePath());
				file_out.createNewFile();
			}

			fin = new FileInputStream(file_in);
			fout = new FileOutputStream(newfilepath);

			byte[] bytes = new byte[1024];

			int c;
			while ((c = fin.read(bytes)) != -1) {
				fout.write(bytes,0,c);
				
			}
			fin.close();
			fout.close();

		} catch (Exception ex) {
			ex.printStackTrace();
			if (fin != null)
				fin.close();
			if (fout != null)
				fout.close();
			throw ex;

		}
		if (file_in != null)
			FileUtil.deleteFile(file_in);

	}

	/**
	 * 根据时间字符串生成按年，月来排的文件系统目录.
	 * 
	 * 
	 * 
	 * @param datestring
	 *            时间字符串 支持 2001-09-08 或20010908两种格式.
	 * 
	 * @return
	 * @throws Exception
	 *             时间格式不正确抛出错误.
	 *             根据时间字符串生成按年，月来排的文件系统目录。
	 */
	public static String dateString2FilePath(String datestring)
			throws Exception {
		String filepath = null;
		String[] strArr = null;
		strArr = datestring.split("-");
		if (strArr.length > 2) {
			filepath = strArr[0] + File.separator + strArr[1] + File.separator;
		}
		if (strArr.length == 1 && strArr[0].length() > 5) {
			filepath = strArr[0].substring(0, 4) + File.separator
					+ strArr[0].substring(4, 6) + File.separator;
		}
		if (filepath == null) {
			throw new Exception("时间格式不正确");
		}
		return filepath;

	}

	/**
	 * 把目录字符串组连接起来生成新的文件目录.
	 * 
	 * 
	 * 
	 * @param pathstrings
	 *            目录字符串数组.
	 * 
	 * @return
	 * @throws Exception
	 *             时间格式不正确抛出错误.
	 *             把目录字符串组连接起来生成新的文件目录。
	 */
	public static String joinFilePaths2NewFilePath(String... pathstrings)
			throws Exception {
		String newpath = "";
		int i = 1;
		for (String path : pathstrings) {
			// 最后的是目录分割符
			if (path.length() > 0
					&& path.lastIndexOf(File.separator) == (path.length() - 1))
				path = path.substring(0, path.length() - 1);
			if (i == 1) {
				newpath = path;
			} else {
				newpath = newpath + File.separator + path;
			}

			i++;
		}
		if (newpath.equals(""))
			throw new Exception("新的目录为空目录");
		return newpath;
	}

	/**
	 * 根据文件路径得到文件名
	 * 
	 * 
	 * 
	 * @param filePath
	 *            文件路径.
	 * 
	 * @return
	 * @throws Exception
	 *             文件路径 为空.
	 *             根据文件路径得到文件名。
	 */
	public static String getFileName(String filePath) throws Exception {
		String fileName = "";
		if (filePath == null)
			throw new Exception("目录为空目录");

		if (filePath.lastIndexOf(File.separator) == -1)
			return filePath;

		fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1,
				filePath.length());
		return fileName;

	}

 
	/**
	 * 生成新的文件,如果存在，则不生成
	 * @return 生成新的文件,如果存在，则不生成
	 * @throws Exception
	 * 生成新的文件,测试文件，,如果存在，则不生成"
	 */
	public static void createNewFile(String filepath) throws IOException {

		File file_out = new File(filepath);
		FileWriter fw = null;
		PrintWriter pw = null;
		System.out.println("exists+++"+file_out.exists());
		if (!file_out.exists())

		{
			System.out.println("exists");

			if (filepath.lastIndexOf(File.separator) != -1) {

				File path = new File(filepath.substring(0, filepath
						.lastIndexOf(File.separator)));
				if (!path.exists()) {

					createFolder(path.getAbsolutePath());

				}

			}

			try {
				file_out.createNewFile();
				fw = new FileWriter(file_out);

				pw = new PrintWriter(fw);
				pw.println("测试内容");
				System.out.println("建立测试");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			} finally {
				if (pw != null)
					pw.close();

				if (fw != null)
					fw.close();

			}

		}

	}

	public static void main(String[] args) {
		try {
			createNewFile("upload\\20112222\\10\\fe8080c52f7c1fed012f7c3499ce033d111111111111.txt");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
